<?php

namespace app\admin\controller;

use app\admin\controller\auth\Admin;
use app\admin\library\Auth;
use app\admin\model\Users;
use app\common\controller\Backend;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use think\exception\ValidateException;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Visiting extends Backend
{

    /**
     * Visiting模型对象
     * @var \app\admin\model\yuyurVisiting
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->name =Users::field("name,id")->select();
        $this->model = new \app\admin\model\Visiting;
        $groupId = AuthGroup::where('name','讲解员')
            ->value('id');
        $authGroupList = AuthGroupAccess::where('group_id',$groupId)
            ->column('uid');
        $speak = DB::table('fa_admin')->whereIn('id',implode(',',$authGroupList))->column('id,nickname');
        $this->view->assign("speak", $speak); //讲解员
        $this->assign("name",$this->name );
        $this->visitime = config("visit_time2");
        $this->assign("vistime",$this->visitime);
        $this->position_type = config("position_type");
        $this->assign("position_type",$this->position_type);
        $this->department = config("department");
        $this->assign("department",$this->department);

    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
//        dd(session("rule_id") );
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if(session("rule_id") == 5 ){
                $total = $this->model
                    ->with(['users'])
                    ->where($where)
                    ->where(["explain"=>1])
//                    ->where("day",">",date("Y-m-d",time()))
                    ->where("day","<=",date("Y-m-d",time()+86400*7))
                    ->order("day desc,between_time desc")
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->with(['users'])
                    ->where($where)
                    ->where(["explain"=>1])
//                    ->where("day",">",date("Y-m-d",time()))
                    ->where("day","<=",date("Y-m-d",time()+86400*7))
                    ->order("day desc,between_time desc")
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }
            else if(session("rule_id") == 3){
                $total = $this->model
                    ->with(['users'])
                    ->where($where)
//                    ->where("day",">",date("Y-m-d",time()))
                    ->where(["admin_id"=>"0"])
                    ->where("day","<=",date("Y-m-d",time()+86400*7))
                    ->order("day desc,between_time desc")
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->with(['users'])
                    ->where($where)
//                    ->where("day",">",date("Y-m-d",time()))
                    ->where("day","<=",date("Y-m-d",time()+86400*7))
                    ->where(["admin_id"=>"0"])
                    ->order("day desc,between_time desc")
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }
            else{
                $total = $this->model
                    ->with(['users'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->with(['users'])
                    ->where($where)
                    ->order("day desc,between_time desc")
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }
            foreach ($list as $row) {
                $row->getRelation('users')->visible(['name']);
            }
            $list = collection($list)->toArray();

            foreach($this->visitime as $k=>$val){
                foreach($list as $key=>$value){
                    if($value['arrival_time']==""){
                        if($k == $value['between_time']){
                            $list[$key]['between_time'] = $val;
                        }
                    }else{
                        $list[$key]['between_time'] = $value['arrival_time'];
                    }
                }
            }
            foreach($list as $key=>$value){
                $list[$key]['venue'] = $value['venue'] == 'A' ? '北山街馆区' :'栖霞岭馆区';
                $list[$key]['explain'] = $value['explain'] == 1 ? '需要' :'不需要';
                $list[$key]['type'] = $value['type'] == 0 ? '个人' :'团体';
                switch ($value['status']){
                    case 0:
                        $list[$key]['status'] = "等待预约";break;
                    case 1:
                        $list[$key]['status'] = "预约中";break;
                    case 4:
                        $list[$key]['status'] = "完成参观";break;
                    case 6:
                        $list[$key]['status'] = "未参观";break;
                    case 3:
                        $list[$key]['status'] = "取消预约";break;
                    case 2:
                        $list[$key]['status'] = "完成评价";break;
                    default:
                        $list[$key]['status'] = "特殊预留";
                }
                $list[$key]['actual_time'] =$value['actual_time']?date("Y-m-d H:i;s",$value['actual_time']):null;
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $code =  str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        if(!$ids)$ids = $this->request->param('id');

        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $groupId = AuthGroup::where('name','讲解员')
            ->value('id');
        $authGroupList = AuthGroupAccess::where('group_id',$groupId)
            ->column('uid');

        $name = DB::table('fa_admin')->whereIn('id',implode(',',$authGroupList))->column('id,nickname');


        $this->view->assign("name", $name); //讲解员

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
//

                    if(isset($params['status'])){
                        if($params['status'] == 6){
                            \app\admin\model\Stoptell::insert(['mobile'=>$params['mobile'],'stop_time'=>time()+(86400*30)]);
//                        Users::where("user_id",$params['user_id'])->update(["status"=>0,"stop_time"=>time()+(86400*30)]);
                        }
                    }
                    if(isset($params['actual_views']) && $params['actual_views']==""){
                        unset($params['actual_views']);
                    }
//                    if(session("rule_id") == 5){
////
//                    }elseif (session("rule_id") == 3){
//
//                    }else{
//                        sendSMS("【五四宪法馆】您好，您的预约已修改，请注意查收",$code,$params['mobile']);
//                    }
//                        dd($params);
//                    $params['code'] = $code;
                    if(session("rule_id") == 5 ){
                        $params['actual_time'] = time();
                    }
                    $result = $row->allowField(true)->save($params);
                    if($params['admin_id']??""){
                         \app\admin\model\Visiting::where("id", $row->id)->update(['status'=>4]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 导入
     */
    public  function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
       $this->importExecl($filePath);
       $this->success();
    }

    /**
     * 使用PHPEXECL导入
     *
     * @param string $file      文件地址
     * @param int    $sheet     工作表sheet(传0则获取第一个sheet)
     * @param int    $columnCnt 列数(传0则自动获取最大列)
     * @param array  $options   操作选项
     *                          array mergeCells 合并单元格数组
     *                          array formula    公式数组
     *                          array format     单元格格式数组
     *
     * @return array
     * @throws Exception
     */
   public   function importExecl($file = '', $sheet = 0, $columnCnt = 0, &$options = [])
    {
        try {
            /* 转码 */
            $file = iconv("utf-8", "gb2312", $file);

            if (empty($file) OR !file_exists($file)) {
                throw new \Exception('文件不存在!');
            }

            /** @var Xlsx $objRead */
            $objRead = IOFactory::createReader('Xlsx');

            if (!$objRead->canRead($file)) {
                /** @var Xls $objRead */
                $objRead = IOFactory::createReader('Xls');

                if (!$objRead->canRead($file)) {
                    throw new \Exception('只支持导入Excel文件！');
                }
            }

            /* 如果不需要获取特殊操作，则只读内容，可以大幅度提升读取Excel效率 */
            empty($options) && $objRead->setReadDataOnly(true);
            /* 建立excel对象 */
            $obj = $objRead->load($file);
            /* 获取指定的sheet表 */
            $currSheet = $obj->getSheet($sheet);

            if (isset($options['mergeCells'])) {
                /* 读取合并行列 */
                $options['mergeCells'] = $currSheet->getMergeCells();
            }

            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑，循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }

            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $data   = [];

            /* 读取内容 */
            for ($_row = 2; $_row <= $rowCnt; $_row++) {
                $isNull = true;
                for ($_column = 1; $_column <= $columnCnt; $_column++) {
                    $cellName = Coordinate::stringFromColumnIndex($_column);
                    $cellId   = $cellName . $_row;
                    $cell     = $currSheet->getCell($cellId);
                    $data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());
                    if (!empty($data[$_row][$cellName])) {
                        $isNull = false;
                    }
                }
                /* 判断是否整行数据为空，是的话删除该行数据 */
                if ($isNull) {
                    unset($data[$_row]);
                }
//                dd($data[$_row]['A']);die();
                foreach($this->name as $k=>$value){
                    if($value['name'] == $data[$_row]['A']){
                        $param['user_id'] = $value['id'];
                    }
                }
                $param['name']       =  $data[$_row]['B'];
                $param['mobile']     =  $data[$_row]['C'];
                $param['venue']      =  $data[$_row]['D'];
                $param['company']    =  $data[$_row]['E'];
                $param['department'] =  $data[$_row]['F'];
                $param['position_type'] =  $data[$_row]['G'];
                $param['views'] =  $data[$_row]['H'];
                $param['explain'] = $data[$_row]['I'] == "需要" ? 1 :0;
                $param['day'] = $data[$_row]['J'];
                foreach ($this->visitime as $k=>$value){
                    if($value == $data[$_row]['K']){
                        $param['between_time'] = $k;
                    }
                }
                $param['between_day'] = $data[$_row]['L'];
                $param['status'] = $data[$_row]['M'] == "预约中" ? 1 :5;
                $param['note'] =  $data[$_row]['N'];
                $param['add_time'] = time();
                \app\admin\model\Visiting::create($param);
            }
            return $data;
        } catch (\Exception $e) {
            throw $e;
        }
    }



    /**
     * 添加
     */
    public function add()
    {
        $code =  str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        $groupId = AuthGroup::where('name','讲解员')
            ->value('id');
        $authGroupList = AuthGroupAccess::where('group_id',$groupId)
            ->column('uid');

        $name = DB::table('fa_admin')->whereIn('id',implode(',',$authGroupList))->column('id,nickname');
        $this->view->assign("name", $name); //讲解员
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
//                    dd($params);
                    if($params['type'] == 0){
                        unset($params['admin_id']);
                    }
//                    if($params['status'] == 5){
//                        $result = \app\admin\model\Visiting::where("day",$params['day'])->where("between_time",$params['between_time'])->find();
//                        sendSMS("【五四宪法馆】您好，您的预约因为特殊情况已被删除，请注意查收",$code,$result['mobile']);
//                        \app\admin\model\Visiting::where("day",$params['day'])->where("between_time",$params['between_time'])->delete();
//                    }
                    $guan = $params['venue']=='A'?'北山街馆区，地址是北山街84号':'栖霞岭馆区，地址是栖霞岭54号';
                    sendSMS("【五四宪法馆】预约成功。预约码：".$code."。您已预约".$params['day'] ."    ".$params['arrival_time']."   " . $guan."，请您携带有效身份证件按时签到参观。团队参观请携带介绍信。取消或改期截止时间为参观前一日14点前。点击".\request()->domain()."查看您的预约信息",$code,$params['mobile']);

                    //                    sendSMS("您好，您预约五四博物馆的已经被申请，验证码为",$code,$params['mobile']);

//                    dd($params);

                    $params['code'] = $code;
                    $params['between_time'] = 0;
//                    dd($params);
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }



    /**
     * 样本导出
     */
    public function export(){
        dd('hello');
       //另一种下载
//       $fileName = $_SERVER['HTTP_HOST'].'/'."uploads/"."1.xlsx";
//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        header(
//            "Content-Disposition:attachment;filename=" . iconv(
//                "utf-8", "GB2312//TRANSLIT", $fileName
//            )
//        );
//        header('Cache-Control: max-age=0');//禁止缓存
//        $savePath = 'php://output';
//        ob_clean();
//        ob_start();
//        $objSpreadsheet = new Spreadsheet();
//        $objWriter = IOFactory::createWriter($objSpreadsheet, 'Xlsx');
//        $objWriter->save($savePath);
       $fileName = "uploads/"."1.xlsx";
        header('Content-Description: File Transfer');
        header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        header("Content-Disposition: attachment; filename=" . basename($fileName));
        header("Content-Transfer-Encoding: binary");
        header("Expires: 0");
        header("Pragma: public");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Length: ' . filesize($fileName));
        ob_clean();
        flush();
        readfile($fileName);
        $this->success();
    }


    /**
     * @根据预约码确认预约记录
     */
    public function confirmFromCode()
    {
        $code = $this->request->param('code');
        $visit_info = \app\admin\model\Visiting::where(['code'=>$code,"explain"=>1,'status'=>1])->where("day",date("Y-m-d",time()))->find();
        if(!$visit_info){
            return info('今天的预约码不存在！', -1, '');
        }
        if($visit_info['status']!=1){

            $status = config('visit_status')[$visit_info['status']];

            return info("预约状态为{$status}不符合操作条件!", -2, '');
        }
//        $res = \app\admin\model\Visiting::where('code',$code)->update(['status'=>4]);

//        if($res){
            return info("预约时间为：".$visit_info['arrival_time'], 1,'',$visit_info);
//        }

    }


    /**
     * 获取调解员
     */
    public function gettiaojie(){
            $data = input("get.");
            $result =\app\admin\model\Schedu::where($data)->with('users')->select();
            return info('操作成功！', 1,'',$result);

    }



    /**
     * 删除
     */
    public function send()
    {
        $code =  str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        $data1 = input("get.");
        $data = json_decode($data1['code'],1);
        foreach($data as $k=>$val){
            if(in_array($val['status'],[2,3,4])) continue;
            $mobile = $val['mobile'];
            $msg = "【五四宪法馆】您好，您的$val[code]预约,$val[venue]$val[day]的参观因为$data1[message]已被取消，请登录平台重新预约,给您带来的不便我们深感抱歉。";

            $this->model->where('id',$val['id'])->setField('status',3);
            sendSMS($msg,'',$mobile);

        }

        return info('成功！'.$msg, 1,'',"");
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        $code =  str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
//                     sendSMS("【五四宪法馆】您好，您的预约因为特殊情况已被删除，请注意查收",$code,$v['mobile']);
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
